package com.whxd.system.main.web;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.whxd.framework.common.config.Global;
import com.whxd.system.user.service.UserService;

/**
 * @author 张世鹏
 * @since 2013-7-1
 */
@Controller
@RequestMapping("/system/upload")
public class HeadUploadCtrl {

	private static Logger logger = LoggerFactory.getLogger(HeadUploadCtrl.class);

	@Autowired
	private UserService userService;

	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");

	// @RequestMapping(value = "/picUpload", method = RequestMethod.POST)
	// public ModelAndView upload(HttpServletRequest request,
	// @RequestParam("uploadFile") MultipartFile file) throws IOException {
	// if (file == null || file.isEmpty()) {
	// logger.info("文件未上传");
	// return new ModelAndView("/pages/system/upload/picUpload", "msg",
	// "请选择文件上传");
	// }
	// String tmpName = file.getOriginalFilename().toLowerCase();
	// if (!(tmpName.endsWith(".png") || tmpName.endsWith(".jpg")
	// || tmpName.endsWith(".jpeg") || tmpName.endsWith(".gif") || tmpName
	// .endsWith(".bmp"))) {
	// logger.info("文件格式错误：" + tmpName);
	// return new ModelAndView("/pages/system/upload/picUpload", "msg",
	// "文件格式错误，只允许上传.png|.jpg|.jpeg|.gif|.bmp格式的图片");
	// }
	// logger.info("文件长度: " + file.getSize());
	// logger.info("文件类型: " + file.getContentType());
	// logger.info("文件原名: " + file.getOriginalFilename());
	// String fileName = sdf.format(new Date()) + file.getOriginalFilename();
	// Thumbnails.of(file.getInputStream()).size(640, 480)
	// .toFile(Global.UPLOAD_FOLDER + fileName);
	// // FileUtils.copyInputStreamToFile(file.getInputStream(),new
	// // File(Global.UPLOAD_FOLDER,fileName));
	// return new ModelAndView("/pages/system/upload/picCrop", "fileName",
	// fileName);
	// }

	@RequestMapping(value = "/picView")
	public void picView(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 获取文件路径
		String imagePath = Global.UPLOAD_FOLDER + fileName;
		response.reset();
		FileInputStream imageFile = null;
		try {
			imageFile = new FileInputStream(imagePath);
		} catch (FileNotFoundException e) {// 如果找不到图片就读取默认的图片
			imageFile = new FileInputStream(request.getServletContext().getRealPath("/static/images/head.jpg"));
			fileName="head.jpg";
		}
		int i = imageFile.available(); // 得到文件大小
		byte data[] = new byte[i];
		imageFile.read(data); // 读数据
		response.setContentType("image/" + fileName.substring(fileName.lastIndexOf("."))); // 设置返回的文件类型
		response.setHeader("Content-Disposition", "filename=" + fileName);
		OutputStream out = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
		out.write(data); // 输出数据
		out.flush();
		out.close();
		imageFile.close();
	}

	// /**
	// * 裁剪图片
	// *
	// * @author 张世鹏
	// * @since 2013-7-1
	// * @param pic
	// * 图片标识
	// * @param x
	// * x坐标
	// * @param y
	// * y坐标
	// * @param w
	// * 宽
	// * @param h
	// * 高
	// * @return
	// * @throws JsonParseException
	// * @throws JsonMappingException
	// * @throws IOException
	// */
	// @RequestMapping("/picCrop")
	// @ResponseBody
	// @RolesAllowed(AuthorityDefine.ROLE_USER)
	// public ReturnObject crop(HttpServletRequest request, String fileName,
	// Integer x, Integer y, Integer w, Integer h)
	// throws JsonParseException, JsonMappingException, IOException {
	// logger.info("裁剪图片,fileName:" + fileName + ",+x:" + x + ",y:" + y
	// + ",w:" + w + ",h:" + h);
	// ReturnObject result = new ReturnObject();
	// try {
	// File realFile = new File(Global.UPLOAD_FOLDER + fileName);
	// String tName = appendSuffix(realFile.getName(), "_thumbnails");
	// Thumbnails.of(realFile).sourceRegion(x, y, w, h).size(256, 256)
	// .toFile(realFile.getParent() + File.separator + tName);
	// result.setSuccess(true);
	// result.setObj(tName);
	// userService.updateUserPic(tName);
	// } catch (Exception e) {
	// result.setMsg("失败：" + e.getMessage());
	// }
	// return result;
	// }

	protected String appendSuffix(String paramString1, String paramString2) {
		String str = "";
		int i = paramString1.lastIndexOf(46);
		if (i != -1) {
			str = paramString1.substring(0, i);
			str = str + paramString2;
			str = str + paramString1.substring(i);
		} else {
			str = paramString1 + paramString2;
		}
		return str;
	}
}
